<style rel="stylesheet/scss" lang="scss" scoped></style>

<template>
    <div>
        <el-select placeholder="请选择" v-model="brandId" :style="styles" filterable clearable>
            <el-option
                v-for="item in brands"
                :key="item.brandId"
                :label="item.brandName"
                :value="item.brandId"
            ></el-option>
        </el-select>
    </div>
</template>

<script>
export default {
    data() {
        return {
            cateId: 0,
            brands: [],
            brandId: null,
            subscribe: null,

            tmpCateId: null
        };
    },
    props: {
        // 编辑时传入品牌ID
        selectBrandId: {
            type: String,
            default() {
                return null;
            }
        },
        styles: {
            type: String,
            default() {
                return 'width: 80%'
            }
        }
    },

    mounted() {
        this.$nextTick(function() {
            //监听三级分类消息的变化
            this.subscribe = PubSub.subscribe("catePathId", (msg, val) => {
                if(val.length > 0) {
                    if(this.cateId) {
                        this.brands = []
                        this.brandId = null
                    }
                    this.cateId = val[val.length - 1];
                    this.getCatBrands();
                } else {
                    this.brands = []
                }
            });
        });
    },
    //监控data中的数据变化
    watch: {
        brandId(val) {
            this.PubSub.publish("brandId", val);
        },
        selectBrandId(val) {
            this.brandId = this.selectBrandId
        }
    },
    methods: {
        getCatBrands() {
            this.$http({
                url: "/mall/pmscategorybrandrelation/list",
                method: "get",
                params: {
                    cateId: this.cateId
                }
            }).then(res => {
                if (this.ResultMessage(res, false)) {
                    this.brands = res.data;
                }
            }).catch(error => {
                this.$notify({ title: "错误", message: error, type: "error" });
            });
        }
    },

    /**
     * 生命周期 - 销毁之前
     */
    beforeDestroy() {
        PubSub.unsubscribe(this.subscribe); //销毁订阅
    }
};
</script>
